package net.kts.setting.language;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import net.kts.transrate.TranslateService;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.simple.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class LanguageUtil {
	private static String language;
	private static boolean mustBeTranslations = true;
	private static SharedPreferences sharedPreferences;
	private static SharedPreferences prefs;
	
	public static void createLanquage(Activity activity){
		sharedPreferences = activity.getSharedPreferences("TranslateWords", Context.MODE_PRIVATE);
		
		Locale systemLocale = activity.getResources().getConfiguration().locale;
		language = systemLocale.getLanguage();
		
		prefs = PreferenceManager.getDefaultSharedPreferences(activity);
		String settingLanguage = prefs.getString("languagelist", "<unset>");
		
		if(language.equals(settingLanguage))
			mustBeTranslations = false;
		
		if(settingLanguage.equals("<unset>")){
			TranslateService.setTranslateTextMap(loadTranslateWords());
			return;
		}
		language = settingLanguage;
		TranslateService.setTranslateTextMap(loadTranslateWords());
	}
	public static boolean storeTranslateWords(Map<String, String> map){
		String words = JSONObject.toJSONString(map);
		SharedPreferences.Editor insSharedPrefEditor = sharedPreferences.edit();
		insSharedPrefEditor.putString(language, words);
		return insSharedPrefEditor.commit();
	}
	public static HashMap<String, String> loadTranslateWords(){
		String json = sharedPreferences.getString(language, "");
		
		HashMap<String,String> result = null;
		try {
			result = new ObjectMapper().readValue(json, HashMap.class);
		} catch (Exception e) {
			Log.e("kts", e.getMessage());
			result = new HashMap<String, String>();
		}
		if(result == null)
			result = new HashMap<String, String>();
		return result;
	}
	public static void updateLanguage(String lang){
		mustBeTranslations = true;
		language = lang;
		String settingLanguage = prefs.getString("languagelist", "<unset>");
//		if(language.equals(settingLanguage)){
//			return;
//		}
		TranslateService.setTranslateTextMap(loadTranslateWords());
		
	}
	public static boolean mustBeTranslations(){
		return mustBeTranslations;
	}
	public static String getCurrentLanguage(){
		return language;
	}
}
